package com.eagleframework.component;

import com.eagleframework.component.aop.AopLogAspect;
import com.eagleframework.component.beans.EagleBeanFactory;
import com.eagleframework.component.beans.EagleReplaceBeanPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 基础组件自动配置
 *
 * @author yaojx
 * @since 1.0.0
 */
@Configuration
@EnableScheduling
@EnableAsync
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class EagleFrameworkComponentAutoConfigure {
    @Bean
    @ConditionalOnMissingBean
    public BeanPostProcessor eagleReplaceBeanPostProcessor() {
        return new EagleReplaceBeanPostProcessor();
    }
    
    /**
     * 提供Bean操作工具
     *
     * @return {@link EagleBeanFactory}
     */
    @Bean
    @ConditionalOnMissingBean
    public EagleBeanFactory eagleBeanFactory() {
        return new EagleBeanFactory();
    }
    
    @Bean
    @ConditionalOnMissingBean
    public AopLogAspect aopLogAspect() {
        return new AopLogAspect();
    }
    
    /**
     * 默认提供的线程池
     *
     * <p>用户自定义可通过提供线程池的Bean即可,该机制确保应用中存在至少一个线程池
     *
     * @return {@link ThreadPoolTaskExecutor} 线程池
     */
    @Bean
    @ConditionalOnMissingBean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(200);
        executor.setQueueCapacity(50);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-eagle-");
        /*
        用于被拒绝任务的处理程序：
        AbortPolicy，它将抛出RejectedExecutionException。
        CallerRunsPolicy，它直接在execute方法的调用线程中运行被拒绝的任务。
        DiscardOldestPolicy，它放弃最旧的未处理请求，然后重试execute。
        DiscardPolicy，默认情况下它将丢弃被拒绝的任务
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
